<?php

namespace addons\yunfood\model;

use addons\yunfood\library\Logic;
use addons\yunfood\library\ModelTrait;
use think\Model;
use traits\model\SoftDelete;

/**
 * 打印机模型
 */
class PrinterDevice extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yunfood_printer_device';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    public function scopeShow($query)
    {
        return $query->where('status', '=', self::STATUS_NORMAL);
    }

    // 门店名称
    public function getShopTextAttr($value, $data)
    {
        return Logic::getShopNames($data['shop_ids']);
    }

    // 品牌
    const BRAND_FEIE      = 'feie';
    const BRAND_YILIANYUN = 'yilianyun';
    const BRAND_ZHONGWU   = 'zhongwu';

    public static function getBrandList()
    {
        return [
            self::BRAND_FEIE      => __('飞鹅'),
            self::BRAND_YILIANYUN => __('易联云'),
            self::BRAND_ZHONGWU   => __('中午'),
        ];
    }

    public function getBrandTextAttr($value, $data)
    {
        $optionList = self::getBrandList();

        return $optionList[$data['brand']] ?? $data['brand'];
    }

    // 飞鹅数据
    public function getFeieDataAttr($value, $data)
    {
        return $data['brand'] == self::BRAND_FEIE ? json_decode($data['config'], true)
            : ['sn' => '', 'key' => ''];
    }

    // 易联云数据
    public function getYilianyunDataAttr($value, $data)
    {
        return $data['brand'] == self::BRAND_YILIANYUN ? json_decode($data['config'], true)
            : ['machine_code' => '', 'msign' => ''];
    }

    // 中午数据
    public function getZhongwuDataAttr($value, $data)
    {
        return $data['brand'] == self::BRAND_ZHONGWU ? json_decode($data['config'], true)
            : ['device_id' => '', 'device_secret' => ''];
    }

    // 打印场景
    const SCENE_ORDER = 1;

    public static function getSceneList()
    {
        return [
            self::SCENE_ORDER => __('下单'),
        ];
    }

    // 状态
    const STATUS_NORMAL = 1;
    const STATUS_HIDDEN = 2;

    public static function getStatusList()
    {
        return [self::STATUS_NORMAL => __('Normal'), self::STATUS_HIDDEN => __('屏蔽')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $optionList = self::getStatusList();

        return $optionList[$data['status']] ?? $data['status'];
    }

    // 获取select列表
    public static function getOptionList()
    {
        $options = [];
        $dataList = PrinterDevice::field(['id', 'name'])->select();
        foreach ($dataList as $item) {
            $options[$item['id']] = $item['name'];
        }

        return $options;
    }
}
